﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using TalksLog.Domain.Account.Entities;
using TalksLog.Domain.Account.Repositores;
using TalksLog.Domain.Core;
using TalksLog.Domain.DomainEvents;

namespace TalksLog.Domain.Account.Services
{
    /// <summary>
    /// 找回密码服务
    /// </summary>
    public class EmailVerificationService
    {
        private IEmailVerificationRepository _emailVerificationRepository;
        private IAccountRepository _accountRepository;
        DomainEventsBusBase<CreateEmailVerificationEvent> _eventsBus;

        public EmailVerificationService(IEmailVerificationRepository emailVerificationRepository, 
            IAccountRepository accountRepository,
            DomainEventsBusBase<CreateEmailVerificationEvent> eventsBus)
        {
            _emailVerificationRepository = emailVerificationRepository;
            _accountRepository = accountRepository;
            _eventsBus = eventsBus;
        }

        public void CreateNewEmailVerification(string email)
        {
            AccountService accountService = new AccountService(_accountRepository);

            if(!accountService.DoesEmailExist(email))
            {
                throw new ArgumentException("未使用该邮箱注册本站");
            }

            EmailVerification emailVerification = EmailVerification.Create(email);
            _emailVerificationRepository.Add(emailVerification);

            _eventsBus.Raise(new CreateEmailVerificationEvent(email, emailVerification.VerificationCode));
        }

        public bool VerifyEmail(string email,string verificationCode)
        {
            var verification = _emailVerificationRepository.FindLatestOneByEmail(email);
            if (verification != null)
            {
                if ((verification.VerificationCode == verificationCode) 
                    && ((DateTime.Now - verification.CreateTime).Minutes < 120)
                    && (verification.VerificationTime == null))
                {
                    verification.VerificationTime = DateTime.Now;
                    _emailVerificationRepository.Update(verification);
                    return true;
                }
            }
            return false;
        }
    }
}
